package nl.will.dirstat;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

public class Directory extends File {

	private HashMap directoryMap = new HashMap();

	private long bytes = 1;

	public Directory(String pathname) {
		super(pathname);
		if (this.isFile()) {
			throw new RuntimeException("Cannot create directory, file is no directory");
		}
		this.directoryMap = new HashMap();
		initialize(directoryMap);

	}

	private Directory(String pathname, HashMap directoryMap) {
		super(pathname);
		if (this.isFile()) {
			throw new RuntimeException("Cannot create directory, file is no directory");
		}
		this.directoryMap = directoryMap;
		initialize(directoryMap);

	}

	private void initialize(HashMap directoryMap) {

		File[] files = super.listFiles();
		for (int j = 0; j < files.length; j++) {
			File file = files[j];
			if (file.isDirectory()) {
				try {
					file = new Directory(file.getCanonicalPath(), this.directoryMap);
				} catch (IOException e) {
					throw new RuntimeException(e);
				}

			}
			this.bytes = this.bytes + file.length();

		}

		directoryMap.put(this.getAbsolutePath(), this);

	}

	public Directory getSubDirectory(String absolutePath) {
		return (Directory) this.directoryMap.get(absolutePath);
	}

	public String toString() {

		try {
			return "\n\nStatistieken directory: " + this.getCanonicalPath() + " has a total size of " + this.bytes
					+ " bytes and " + this.listFiles().length + " files\n";
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public long length() {
		return bytes;
	}

	public File[] listFiles() {
		File[] files = super.listFiles();
		File[] newFiles = new File[files.length];
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (file.isDirectory()) {
				try {
					file = (Directory) this.getSubDirectory(file.getCanonicalPath());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			newFiles[i] = file;
		}
		return newFiles;
	}

}
